package com.sea.base.widget

import android.app.Activity
import android.content.Context
import android.content.res.TypedArray
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.custom.widget.R
import com.sea.base.databinding.BaseActionBarBinding
import com.sea.base.ext.global.dp
import com.sea.base.ext.view.FrameLayoutLayoutParams
import com.sea.base.ext.view.getChildOrNull
import com.sea.base.ext.view.realContext
import com.sea.base.ext.view.setOnFastClickListener
import com.sea.base.ext.view.toDrawable
import com.sea.base.utils.ActivityStackManager

/**
 * 通用头部
 */
class BaseActionBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private val suggestActivityContext
        get() = (realContext as? Activity) ?: ActivityStackManager.getCurrentActivity()

    private val vb = BaseActionBarBinding.inflate(LayoutInflater.from(context), this)

    init {
        minimumHeight = 44.dp
        if (attrs != null) {
            val ta: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.BaseActionBar)
            //标题
            val title = ta.getString(R.styleable.BaseActionBar_title)
            if (!title.isNullOrEmpty()) {
                setTitleText(title)
            }

            //左边的返回
            val backDrawable = ta.getDrawable(R.styleable.BaseActionBar_backRes)
            if (backDrawable != null) {
                leftView.setImageDrawable(backDrawable)
            }
            leftView.isVisible = ta.getBoolean(R.styleable.BaseActionBar_backVisible, true)

            //x号
            closeView.isVisible = ta.getBoolean(R.styleable.BaseActionBar_closeVisible, false)

            //右边的图片
            val rightRes = ta.getResourceId(R.styleable.BaseActionBar_rightRes, 0)
            if (rightRes != 0) {
                setRightImage(rightRes.toDrawable)
            }

            //设置右边的文字
            val rightText = ta.getString(R.styleable.BaseActionBar_rightText)
            val rightTextColor = ta.getColor(R.styleable.BaseActionBar_rightTextColor, 0)
            val rightTextSize =
                ta.getDimensionPixelSize(R.styleable.BaseActionBar_rightTextSize, -1)
            if (!rightText.isNullOrEmpty()) {
                setRightText(rightText, rightTextColor, rightTextSize)
            }

            ta.recycle()
        }

        leftView.setOnFastClickListener { onLeftClick?.invoke(it) }
        closeView.setOnFastClickListener { suggestActivityContext?.finish() }
        titleView.setOnFastClickListener { onTitleClick?.invoke(it) }
        vb.flRight.setOnFastClickListener { onRightClick?.invoke(it) }
    }

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 公共方法
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    var onLeftClick: ((View) -> Unit)? = { suggestActivityContext?.finish() }
    var onTitleClick: ((View) -> Unit)? = null
    var onRightClick: ((View) -> Unit)? = null

    var titleText: CharSequence?
        get() = titleView.text
        set(value) {
            setTitleText(value)
        }

    /**
     * 设置标题
     */
    fun setTitleText(str: CharSequence?, @ColorInt textColorInt: Int? = null) {
        titleView.text = str
        if (textColorInt != null) {
            titleView.setTextColor(textColorInt)
        }
    }

    /**
     * 设置右边文字
     * @param textSizePx 如：1.screenRatio
     */
    @JvmOverloads
    fun setRightText(
        text: CharSequence?,
        @ColorInt textColorInt: Int = 0,
        textSizePx: Int = 16.dp
    ): TextView {
        //右边的文字
        var tvRight = rightView as? TextView
        if (tvRight == null) {
            tvRight = AppCompatTextView(context)
            tvRight.setTextColor(
                if (textColorInt == 0) ContextCompat.getColor(context, com.sea.base.R.color.c_000)
                else textColorInt
            )
            tvRight.setTextSize(
                TypedValue.COMPLEX_UNIT_PX,
                (if (textSizePx >= 0) textSizePx else 14.dp).toFloat()
            )
        } else {
            if (textColorInt != 0) {
                tvRight.setTextColor(textColorInt)
            }
            if (textSizePx >= 0) {
                tvRight.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSizePx.toFloat())
            }
        }
        tvRight.gravity = Gravity.CENTER
        tvRight.text = text
        tvRight.setPadding(20.dp, 0, 20.dp, 0)
        rightView = tvRight
        return tvRight
    }

    /**
     * 设置右边图片
     */
    fun setRightImage(drawable: Drawable?): ImageView {
        val iv = AppCompatImageView(context)
        iv.setImageDrawable(drawable)
        iv.scaleType = ImageView.ScaleType.CENTER
        iv.setPadding(20.dp, 0, 20.dp, 0)
        rightView = iv
        return iv
    }

    /**
     * 自定义右边样式
     */
    var rightView: View?
        get() = vb.flRight.getChildOrNull(0)
        set(value) {
            vb.flRight.removeAllViews()
            if (value != null) {
                if (value.layoutParams == null) {
                    value.layoutParams = FrameLayoutLayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.MATCH_PARENT
                    )
                }
                vb.flRight.addView(value)
            }
        }

    /**
     * 获得返回的iv对象(注意返回键有padding属性)
     */
    val leftView get() = vb.ivLeft

    /**
     * 获得标题view
     */
    val titleView get() = vb.tvTitle

    /**
     * 获得x号view
     */
    val closeView get() = vb.ivClose
}